package com.s63.modules.token;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.s63.modules.security.LoginUser;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;

import java.time.Duration;
import java.util.UUID;

public class DefaultTokenService implements ITokenService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @SneakyThrows
    public Token createToken(LoginUser user) {
        String uuid = UUID.randomUUID().toString();
        Token token = new Token();
        token.setToken(uuid);
        token.setNickName(user.getUser().getNickName());
        // 缓存到redis
        stringRedisTemplate.opsForValue().set("s63:ss:login:" + uuid, objectMapper.writeValueAsString(user), Duration.ofMinutes(15));
        return token;
    }

    @Override
    public boolean removeToken(String token) {
        return stringRedisTemplate.delete("s63:ss:login:" + token);
    }

    @Override
    @SneakyThrows
    public LoginUser getLoginUser(String token) {
        String json = stringRedisTemplate.opsForValue().get("s63:ss:login:" + token);
        Assert.notNull(json, "无效的token");
        return objectMapper.readValue(json, LoginUser.class);
    }
}
